<?php 
function get_css_js_dir($arr,$type){
	$path='';
	foreach($arr as $v){
		$path.=$v;
	}
	$path=ez_crc32($path);
	if(defined('ACT')){
		$path=ACT.'_'.$path;
	}
	if(defined('MOD')){
		$path=MOD.'_'.$path;
	}
	
	$path='data/'.$type.'/'.$path.'.'.$type;
	return $path;
}


function thumb($imgurl, $width = 100, $height = 100 ,$autocut = 1, $smallpic = 'nopic.gif') {
	global $webset;
	$upload_url = SITEURL."/";
	$upload_path =EZROOT."/";
	if(empty($imgurl)) return $upload_url."upload/".$smallpic;
	$imgurl_replace= str_replace($upload_url, '', $imgurl);
  
	if(!extension_loaded('gd') || strpos($imgurl_replace, '://')) return $imgurl;
	if(!file_exists($upload_path.$imgurl_replace)) return $upload_url."upload/".$smallpic;
 
	list($width_t, $height_t, $type, $attr) = getimagesize($upload_path.$imgurl_replace);
	if($width>=$width_t || $height>=$height_t) return $upload_url.$imgurl;

	$newimgurl = dirname($imgurl_replace).'/thumb_'.$width.'_'.$height.'_'.basename($imgurl_replace);
	if(file_exists($upload_path.$newimgurl)) return $upload_url.$newimgurl;

	if(!is_object($image)) {
		$image = new ThumbHandler();
	}
    $image->setSrcImg($upload_path.$imgurl);
    $image->setDstImg($upload_path.$newimgurl);
    $image->setCutType($autocut);
    if($image->createImg($width,$height)){
        return $upload_url.$newimgurl;
        
    }else{
        return $upload_url.$imgurl;
        
    }

}


function curl_email($smtp, $username, $password, $from_email, $to_email, $from_name, $title, $content) {
	list ($msec, $sec) = explode(" ", microtime());
	$curl_session = curl_init();
	$header[] = "HELO localhost";
	$header[] = "AUTH LOGIN " . base64_encode($username);
	$header[] = base64_encode($password);
	$header[] = "MAIL FROM:<" . $from_email . ">";
	$header[] = "RCPT TO:<" . $to_email . ">";
	$header[] = "DATA";
	$header[] = "MIME-Version:1.0
Content-Type:text/html
To: " . $to_email . "
From: " . $from_name . "<" . $from_email . ">
Subject: " . $title . "
Date: " . date('r') . "
X-Mailer:By Redhat (PHP/5.3.8)
Message-ID: <" . date("YmdHis", $sec) . "." . ($msec * 1000000) . "." . $from_email . ">

" . $content;
	$header[] = "\r\n.\r\n";
	$header[] = "QUIT";

	$content = '';
	foreach ($header as $v) {
		$content .= $v . "\r\n";
	}

	/* 基本设置 */
	curl_setopt($curl_session, CURLOPT_URL, $smtp);
	curl_setopt($curl_session, CURLOPT_PORT, 25);

	curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true); //把结果返回，而非直接输出
	curl_setopt($curl_session, CURLOPT_CONNECTTIMEOUT, 15); //超时时间

	curl_setopt($curl_session, CURLOPT_CUSTOMREQUEST, $content);

	$http_response = curl_exec($curl_session);
	curl_close($curl_session);
	return $http_response;
}

function mail_send($to, $title, $html, $from='',  $usepassword='', $smtp='',$type=1) {
	global $webset;
	$type=$webset['smtp']['type'];
	
	if($type==2){
        $headers = "MIME-Version: 1.0" . "\r\n";
		$headers .= "Content-type:text/html;charset=utf-8" . "\r\n";
		if($from!=''){
			$headers .= 'From: <'.$from.'>' . "\r\n";
		}
        $re=mail($to,$title,$html,$headers);
		if ($re==1) {
		    $mymsg = 1;
	    } else {
		    $mymsg = 0;
	    }
		return $mymsg;
	}

	$from=$from?$from:$webset['smtp']['name'];
	$usepassword=$usepassword?$usepassword:$webset['smtp']['pwd'];
	$smtp=$smtp?$smtp:$webset['smtp']['host'];
	unset($webset);
	
	if($from=='' || $usepassword=='' || $smtp==''){
		return 0;
	}
	
	$fromname=WEBNICK;
	$usename=$from;
	
	if (!function_exists('fsockopen') && !function_exists('pfsockopen')) {
		if(!function_exists('curl_exec')){
			return 'curl模块，fsockopen或者pfsockopen函数不可用，联系空间商为您开启此函数';
		}
        
		curl_email($smtp, $usename, $usepassword, $from, $to, $fromname, $title, $html);
		return 1;
	}
	if(!class_exists('PHPMailer')){include(EZROOT.'/comm/class.phpmailer.php');}

	$mail = new PHPMailer();
	//$mail->SMTPDebug  = 3;
	$mail->CharSet = "UTF-8"; // charset
	$mail->Encoding = "base64";
	$mail->IsSMTP(); // telling the class to use SMTP

	//邮件系统配置
	$mail->SMTPAuth = true;
	$mail->Host = $smtp; // SMTP server
	$mail->Username = $usename; // SMTP account username
	$mail->Password = $usepassword; // SMTP account password

	$mail->From = $from; //必填，发件人Email
	$mail->FromName = $fromname; //必填，发件人昵称或姓名

	$mail->WordWrap = 50; // 自动换行的字数
	$mail->IsHTML(true); // 以 HTML发送

	//主题
	$mail->Subject = (isset ($title)) ? $title : ''; //必填，邮件标题（主题）

	//邮件主体
	$mail->MsgHTML($html);

	//发送地址
	if ($to) {
		$address = explode("|", $to);
		foreach ($address AS $key => $val) {
			$mail->AddAddress($val, "");
		}
	}
	if (!$mail->Send()) {
		$mymsg = 0;
	} else {
		$mymsg = 1;
	}
	/*$args = func_get_args();
	$args['re']=$mymsg;
	$args['from']=$from;
	$args['usepassword']=$usepassword;
	$args['smtp']=$smtp;
	$args['html']=$html;
	ez_file_put('aaaa.txt',var_export($args,1)."\r\n",FILE_APPEND);*/
	return $mymsg;
}

// count only chinese words
function str_utf8_chinese_word_count($str = ""){
	$utf8_chinese_pattern="/[\x{4e00}-\x{9fff}\x{f900}-\x{faff}]/u";
	$utf8_symbol_pattern="/[\x{ff00}-\x{ffef}\x{2000}-\x{206F}]/u";
    $str = preg_replace($utf8_symbol_pattern, "", $str);
    return preg_match_all($utf8_chinese_pattern, $str, $arr);
}
// count only english words
function str_utf8_english_count($str = ""){
	$utf8_chinese_pattern="/[\x{4e00}-\x{9fff}\x{f900}-\x{faff}]/u";
	$utf8_symbol_pattern="/[\x{ff00}-\x{ffef}\x{2000}-\x{206F}]/u";
    $str = preg_replace($utf8_symbol_pattern, "", $str);
    return strlen(preg_replace($utf8_chinese_pattern, "", $str));
}
// count both chinese and english
function str_utf8_mix_word_count($str = ""){
	$utf8_chinese_pattern="/[\x{4e00}-\x{9fff}\x{f900}-\x{faff}]/u";
	$utf8_symbol_pattern="/[\x{ff00}-\x{ffef}\x{2000}-\x{206F}]/u";
    $str = preg_replace($utf8_symbol_pattern, "", $str);
    return str_utf8_chinese_word_count($str) + strlen(preg_replace($utf8_chinese_pattern, "", $str));
}

function authcode($string, $operation = 'DECODE', $key=EZKEY, $expiry = 0) {
	$ckey_length = 4; // 随机密钥长度 取值 0-32;
	// 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
	// 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
	// 当此值为 0 时，则不产生随机密钥

	//取消UC_KEY，改为必须传入$key才能运行
	if (empty ($key)) {
		exit ('PARAM $key IS EMPTY! ENCODE/DECODE IS NOT WORK!');
	} else {
		$key = md5($key);
	}

	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), - $ckey_length)) : '';

	$cryptkey = $keya . md5($keya . $keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry +TIME : 0) . substr(md5($string . $keyb), 0, 16) . $string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array ();
	for ($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for ($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for ($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a +1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if ($operation == 'DECODE') {
		if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - TIME > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc . str_replace('=', '', base64_encode($result));
	}
}

function PutInfo($msg, $url = '') {
	$title = '系统提示';
	$jump='';
	$meta='';
	if(is_numeric($url) && $url<0){
	    $jump='history.go('.$url.');';
	}
	elseif($url!=''){
	    $meta="<meta http-equiv='refresh' content='1;url=".$url."' />";
	}
	$msginfo = "<html>\n<head>
		<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />\r\n" . $meta . "
		<title>" . $title . "</title>
		<base target='_self'/>\n
		<script>setTimeout(function(){".$jump."},1000);</script>
		</head>\n<body style='text-align:center'>\n
		<br/>
		<div style='margin:auto;width:400px;'>
		<div style='width:400px; padding-top:4px;height:24;font-size:10pt;border-left:1px solid #cccccc;border-top:1px solid #cccccc;border-right:1px solid #cccccc;background-color:#DBEEBD; text-align:center'>" . $title . "</div>
		<div style='width:400px;height:100px;font-size:10pt;border:1px solid #cccccc;background-color:#F4FAEB; text-align:center'>
		<span style='line-height:160%'><br/>".$msg."</span></div></div>";
	echo $msginfo . "\n</body>\n</html>";ez_exit();
}

function upload($uploadname,$saved_upload_name='',$savepath="upload"){
	if (is_uploaded_file($_FILES[$uploadname]['tmp_name'])) {
	    $upload=fs('pic_upload');
		$upload->out_file_dir=EZROOT.'/'.$savepath;
		$upload->upload_form_field = $uploadname;
		$upload->saved_upload_name = $saved_upload_name;
		$upload->upload_process();
		$file_name=$upload->saved_upload_name;
        
        
		$file_name=str_replace(EZROOT.'/','',$file_name);
        $list=array(
        "filename"=>$upload->original_file_name,
        "saved_upload_name"=>$file_name,
        "attachmentSize"=>$upload->original_file_size,
        "is_image"=>$upload->is_image,
        "file_extension"=>$upload->file_extension,
        );
        
        //$attachmentPath=$upload->saved_upload_name;
        //$fileName=$upload->original_file_name;
        //$attachmentSize=$upload->original_file_size;
        //$is_image=$upload->is_image;
        
		if ($upload->error_no) {
			switch ($upload->error_no) {
				case 1 : // No upload
					$err = 201;
					break;
				case 2 :
				case 5 : // Invalid file ext
					$err = 202;
					break;
				case 3 : // Too big...
					$err = 203;
					break;
				case 4 : // Cannot move uploaded file
					$err = 204;
					break;
			}
			return $err;
		}
		else{
		    return $list;
		}
	}
	return 1;
}
function upload_csv($uploadname){
    $file = $_FILES[$uploadname];
    $file_type = substr(strstr($file['name'],'.'),1);
    // 检查文件格式
    if ($file_type != 'csv'){
         return -1;//文件格式不对,请重新上传!

    }
    $handle = fopen($file['tmp_name'],"r");
    @$str=fread($$handle,filesize($file['tmp_name']));
    $file_encoding = mb_detect_encoding($str);
    
    // 检查文件编码
    if ($file_encoding != 'ASCII'){
        return -2;//文件编码错误,请重新上传!
        exit;
    }
    
    $row = 0;
    while ($data = fgetcsv($handle,1000,',')){
        //echo "<font color=red>$row</font>";  //可以知道总共有多少行
        $row++;
        if ($row == 1)
        continue;
        $num = count($data);
        // 这里会依次输出每行当中每个单元格的数据
        for ($i=0; $i<$num; $i++){
            $result.=$data[$i].",";
            // 在这里对数据进行处理
        }
    }
    return $result;
}
function template_parse($str){
	$str=strip_tags($str);
	$str=trim($str);
	
	$s=str_replace('if ','',$str);
	
	preg_match_all('/\{(.*?)\}/',$s,$a);
	foreach($a[1] as $v){
		if(preg_match('/[\n\r\t\s\{\}]+/i', $v)){
			jump(-1,'模板解析失败！');
		}
	}
	
	$dabger='\(|\)|"|;|_post|_get|_request';
	if(preg_match('#'.$dabger.'#i',$str)){
	    jump(-1,'模板解析失败！');
	}
	
	$functions = get_defined_functions();
	$functions=$functions['internal'];
	
	$ignore_functions=array('date','time','sleep','file','mail','sort','end','next','key','min','max','ord','_');

	foreach($functions as $v){
		if(!in_array($v,$ignore_functions)){
			if(strpos($str,$v)){
				jump(-1,'模板解析失败！'.$v);
			}
		}
	}
	
	//特殊变量替换数组
	$a=include(EZROOT.'/data/template_replace.php');
	
	$str = strtr($str,$a);
	$str = preg_replace("/\{if\s+(.+?)\}/","<?php if(\\1) {?>",$str);
	$str = preg_replace("/\{else\}/","<?php } else { ?>",$str);
	$str = preg_replace("/\{elseif\s+(.+?)\}/","<?php } elseif (\\1) {?>",$str);
	$str = preg_replace("/\{\/if\}/","<?php } ?>",$str);
	$str = preg_replace("/\{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/","<?php echo \\1;?>",$str);
	$str = preg_replace("/\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/","<?php echo \\1;?>",$str);
	$str = preg_replace("/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/","<?php echo \\1;?>",$str);
	$str = preg_replace("/\{(\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\}/es", "addquote('<?php echo \\1;?>')",$str);
	$str = preg_replace("/\{([A-Z_\x7f-\xff][A-Z0-9_\x7f-\xff]*)\}/s", "<?php echo \\1;?>",$str);
	return $str;
}




function get_rand($proArr) { 
    $result = ''; 
 
    $proSum = array_sum($proArr); 
    $arr=array();
    $i=1;
    foreach ($proArr as $key => $proCur) { 
        $arr[$key]=array($i,$i+$proCur-1);
        $i=$i+$proCur;
    }
    $randNum = mt_rand(1, $proSum); 
    $result=0;
    foreach ($arr as $key => $val) {
        if(($randNum>=$val[0]) and ($randNum<=$val[1])){
            $result = $key; 
            break;             
        }
        
    }
    unset ($proArr); 
    return $result; 
} 

function getmallSelect($mallid,$fname,$pompt='',$id = 0){
	global $ezhand;
    if($mallid<0){
        
        return "";
    }
	$hd_arr = $ezhand->select_all('mall','id,title',' parent_id='.$mallid.' order by title');
    $html="";
    foreach ( $hd_arr as $category ) {
		
        $select_id = $category ['id'];
		$name = $category ['title'];
		$selected = $select_id==$id?'selected':'';
		$html.="<option value=\"".$select_id."\" ".$selected.">".$name."</option>\n";        
        
        
    }
    
  if($fname=="level2"){
     echo '<select id="'.$fname.'" name="'.$fname.'" onchange="javascript:changelevel2()">';
  }else{
     echo '<select id="'.$fname.'" name="'.$fname.'">';  
  }
  
   echo '<option value="-1">'.$pompt.'</option>';

    if(!empty($html)){
        echo $html;
    }
        echo '</select>';
    
    
    
 

}
function set_positions($tid,$relatepos,$catid=0,$modelid=0){
    global $ezhand;
    if(empty($tid)){
        return 0;
    }
    $relatepos=trim($relatepos);
    $ezhand->delete('position_data','tid="'.$tid.'"');
    if(empty($relatepos)){
         return 0;
    }else{
        $clist=explode(",",$relatepos);
        while(list($k,$cid)=each($clist)){
            $d=array("tid"=>$tid,
            "posid"=>$cid,
            "catid"=>$catid,
            "modelid"=>$modelid
            );    
            $ezhand->insert("position_data",$d);
        }
         return 1;
        
    }
         
}
function set_relatecat($tid,$relatecat){
    global $ezhand;
    if(empty($tid)){
        return 0;
    }
    $relatecat=trim($relatecat);

    $ezhand->delete('relatecat','tid="'.$tid.'"');
    if(empty($relatecat)){
         return 0;
    }else{
        $clist=explode(",",$relatecat);
        while(list($k,$cid)=each($clist)){
            $d=array("tid"=>$tid,
            "catid"=>$cid
            );    
            $ezhand->insert("relatecat",$d);
        }
         return 1;
        
    }

}

function get_nav_catid2($catid){
   global $ezhand;

    $arr = $ezhand->select('category','id,catname,parentid,catdir,level',"id=".$catid);
    if(empty($arr)){
        return "";
    }
    if($arr["level"]==0){
     //   $html="<a href=\"".SITEURL."/category".$arr["id"].".html\">".$arr["catname"]."</a>";
    }else{
        $html="&gt; ".$arr["catname"]."";
    }
    if(!empty($arr["parentid"])){
        
        $html1=get_nav_catid2($arr["parentid"]);
    }
    if($html1<>""){
        $html=$html1.$html;
    }
   return $html;

}


function get_nav_catid($catid){
   global $ezhand;

    $arr = $ezhand->select('category','id,catname,parentid,catdir,level',"id=".$catid);
    if(empty($arr)){
        return "";
    }
    if($arr["level"]==0){
     //   $html="<a href=\"".SITEURL."/category".$arr["id"].".html\">".$arr["catname"]."</a>";
    }else{
        $html="<li>&gt; <a href=\"".tu($catid,"0")."\">".$arr["catname"]."</a></li>";
    }
    if(!empty($arr["parentid"])){
        
        $html1=get_nav_catid($arr["parentid"]);
    }
    if($html1<>""){
        $html=$html1.$html;
    }
   return $html;

}


function get_subcatid($catid){
   global $ezhand;
   
    $arr = $ezhand->select_all('category','id',"parentid=".$catid);
    if(empty($arr)){
        $arr[]=$catid;
        return $arr;
    }
   
    $arr2=array();
    while(list($k1,$v1)=each($arr)){
       $arr2[]=$v1["id"]; 
    }
   
    if(!empty($arr)){
        reset($arr);
      while(list($k,$v)=each($arr)){
        $list1=get_subcatid($v["id"]);

        if(!empty($list1)){
            $arr2=array_merge($arr2,$list1);
        }
      }
      
        
    }else{
        return "";
    }
    if(!in_array($catid,$arr2)){
     $arr2[]=$catid;
    }
   
   return $arr2;

}
function get_zhipo_data($num=10,$order="id"){
    global $ezhand;
 
    $arr = $ezhand->select_all('zhibo_subject','*',' enabled=1 order by '.$order.' desc limit '.$num);
    
    return $arr;    

}
function get_bbs_data($fid=0,$thumb=0,$num=5,$orders="tid",$postinfo=0,$explist=array()){
    global $ezhand;
    $where=" displayorder>-1 ";
    if($fid>0){
        $where.=" and fid=".$fid;
    }
    if($thumb>0){
        $where.=" and attachment=2";
    }
    if(!empty($explist)){
      $where.=" and tid not in (".join(",",$explist).")";  
    }
    
    $list=array();
    $sql="select tid,fid,author,authorid,subject,dateline from ultrax.pre_forum_thread where ".$where." order by ".$orders." desc limit ".$num;
    $res=$ezhand->query($sql);
    while($row=$ezhand->fetch_array($res)){
        if($thumb>0){
            $tableid=substr($row[tid],-1,1);
            $sql="select attachment from ultrax.pre_forum_attachment_".$tableid." where tid=".$row["tid"]." limit 1";
            $res2=$ezhand->query($sql);
            $row2=$ezhand->fetch_array($res2);
            if(!empty($row2)){
               $row["attachment"]=$row2["attachment"];
            }
            if($postinfo>0){
            $sql="select message from ultrax.pre_forum_post where tid=".$row["tid"]." and first=1 limit 1";
            $res3=$ezhand->query($sql);
            $row3=$ezhand->fetch_array($res3);
            if(!empty($row3)){
               $row["message"]=$row3["message"];
               //messagecutstr  怎么处理？
            }                
                
            }
        }
        $list[]=$row;
    }
    return $list;
}
function get_att_data($id,$table){
    global $ezhand;
    if(is_numeric($id)){
    $pidname=substr($table,0,1);
    $arr2 = $ezhand->select($table,$pidname.'_name',$pidname.'_id='.$id);
    }else{
    $arr2="";    
    }
    return $arr2;
}


function get_new_data($catid,$num=10,$order="id",$exceptlist=array(),$getuint=0,$havethumb=0){
    global $ezhand;
    $arr=array();
    $whe=" status=99 ";
    if(!empty($catid)){
        $catlist=get_subcatid($catid);
        if(!empty($catlist)){
            
             $whe.=" and catid in (".implode(",",$catlist).")";
        }
        
       
        
    }
    if(!empty($exceptlist)){
        $whe.=" and id not in (".implode(",",$exceptlist).")";
        
    }
    if($havethumb==1){
        $whe.=" and thumb<>''";
    }
    $arr = $ezhand->select_all('thread','*',$whe.' order by '.$order.' desc limit '.$num);
    if($getuint>0){
        $arrlist=array();
        while(list($k,$v)=each($arr)){
            $arr2 = $ezhand->select('news','source,authorunit','tid='.$v["id"]);
            $v["source"]=$arr2["source"];
            $v["authorunit"]=$arr2["authorunit"];
            $arrlist[]=$v;   
        }
        return $arrlist;
    }else{
        return $arr;    
    }
    
     

}
function get_link_data($linktype=1,$num=24){
    global $ezhand;
    $arr = $ezhand->select_all('link','*',' linktype='.$linktype.' order by listorder asc,id desc limit '.$num);
    return $arr; 
}
function get_vote_data($posid,$num=1){
    global $ezhand;    
    $arr=array();
    if(empty($posid)){
        return $arr;
    }   
    $vlist=array();
    $arr = $ezhand->select_all('vote_subject','*',' posid='.$posid.' and enabled=1 order by subjectid desc limit '.$num);
    if(!empty($arr)){
        
    while(list($k,$v)=each($arr)){
        $subjectid=$v["subjectid"];
        $arr2 = $ezhand->select_all('vote_option','*',' subjectid='.$subjectid.' order by optionid ');
        $v["oplist"]=$arr2;
        $vlist[]=$v;
    }
    
    }
    return $vlist; 
}
function get_catname($catid){
    global $ezhand; 
    if(empty($catid)){
        return "";
    }
    $cat_arr = $ezhand->select('category','catname',' id='.$catid.'');
    return $cat_arr;
    
}

function getother($table,$pre,$order,$idstr,$t=0){
    global $ezhand;
    $otherstr='';

    $arr = $ezhand->select_all($table,"{$pre}_id,{$pre}_name",'1 order by '.$order);

    
    if($t==0){
        while(list($k,$row)=each($arr)){
            $otherstr.="<option value=\"{$row["{$pre}_id"]}\"";
            if ($row["{$pre}_id"]==$idstr) $otherstr.=" selected=\"selected\"";
            $otherstr.=">{$row["{$pre}_name"]}</option>\r\n";
        }
    }else{
        while(list($k,$row)=each($arr)){
            $otherstr.="<option value=\"{$row["{$pre}_name"]}\"";
            if ($row["{$pre}_name"]==$idstr) $otherstr.=" selected=\"selected\"";
            $otherstr.=">{$row["{$pre}_name"]}</option>\r\n";
        }
    }
    return $otherstr;
}

function get_position_data($posid,$num=2,$catid=0,$getuint=0){
    global $ezhand;
    
    $arr=array();
    if(empty($posid)){
        return $arr;
    }   
    $whe="";  
    if(!empty($catid)){
        
        $whe=" and d.catid=".$catid;
    }
    
    $arr = $ezhand->select_all('thread t,position_data d','t.*',' t.id=d.tid and t.status=99 and d.posid='.$posid.' '.$whe.' order by d.listorder asc,t.id desc limit '.$num);
    
    if($getuint>0){
        $arrlist=array();
        while(list($k,$v)=each($arr)){
            $arr2 = $ezhand->select('news','source,authorunit','tid='.$v["id"]);
            $v["source"]=$arr2["source"];
            $v["authorunit"]=$arr2["authorunit"];
            $arrlist[]=$v;   
        }
        return $arrlist;
    }else{
        return $arr;    
    }
        
   // return $arr; 
}

function get_relatecat($catid){
     global $ezhand;
     if(empty($catid)){
        return "";
     }
 	$hd_arr = $ezhand->select_all('category','catname',' id in ('.$catid.')');
    $list=array();
    foreach ( $hd_arr as $category ) {
        $list[]=$category["catname"]; 
    }

    return implode(',',$list);
    
}
function getmsgfrom($r){
    global $ezhand;     
    if(empty($r)){
        return "";
    }
    if($r["usertype"]==82){
        $arr2 = "<font color=blue><b>".$ezhand->select("thread","title","id=".$r["from_uid"])."</b></font>";    
    }elseif($r["usertype"]==84){
         $arr2 = "<font color=red><b>".$ezhand->select("thread","title","id=".$r["from_uid"])."</b></font>";    
    }elseif($r["usertype"]==0){
        $arr2 = "<font color=blue><b>北京网络行业协会：".$r["send_from_id"]."</b></font>";  
    }
    return $arr2;
        
    
}
function get_linkcat($scid){
     global $ezhand;    
     if(empty($scid)){
        return "";
     }
 	$hd_arr = $ezhand->select_all('thread','title',' id in ('.$scid.')');
    $list=array();
    foreach ( $hd_arr as $category ) {
        $list[]=$category["title"]; 
        
    }
    
    return implode(',',$list);    
             
}

function get_linkspecial($spid){
     global $ezhand;
     if(empty($spid)){
        return "";
     }
 	$hd_arr = $ezhand->select_all('special','title',' id in ('.$spid.')');
    $list=array();
    foreach ( $hd_arr as $category ) {
        $list[]=$category["title"]; 
    }
    
    return implode(',',$list);     
     
    
}
function set_linkspecial($tid,$spid){
    global $ezhand;
    $spid=trim($spid);

    $ezhand->delete('linkspecial','tid="'.$tid.'"');
    if(empty($spid)){
        
         return 0;
    }else{
        $clist=explode(",",$spid);
        while(list($k,$cid)=each($clist)){
            $d=array("tid"=>$tid,
            "spid"=>$cid
            );    
            $ezhand->insert("linkspecial",$d);
        }
        
         return 1;
    }

}



/**
 * 栏目分类下拉框 <option></option>
 *
 * @param int $pid
 * @param int $id
 * @param int $level
 */
function getCategorySelect($select_id=0,$id = 0,$level = 0){
	global $ezhand;
	global $mod_tag;
	if(!isset($mod_tag)){
	    $mod_tag=MOD;
	}
	$category_arr = $ezhand->select_all('type','*','pid="'.$id.'" and tag="'.$mod_tag.'" order by sort desc');//print_r($category_arr);exit;
	for($lev = 0; $lev < $level * 2 - 1; $lev++) {
		$level_nbsp .= "&nbsp;";
	}
	if ($level++)
		$level_nbsp .= "┝";
	foreach ( $category_arr as $category ) {
		$id = $category ['id'];
		$name = $category ['title'];
		$selected = $select_id==$id?'selected':'';
		echo "<option value=\"".$id."\" ".$selected.">".$level_nbsp . " " . $name."</option>\n";
		if($id>0){
		    getCategorySelect ($select_id, $id, $level);
		}
	}
}



function spm($url){
	if($url==''){return '';}
	$EZKEY=21114278;
	if(strpos($url,'&spm=2014.'.$EZKEY.'.')!==false){
		return $url;
	}	
	elseif(strpos($url,'&spm=')!==false){
		preg_match('#&spm=2014\.(\d+)\.\d+\.\d+#',$url,$a);
		$spm='2014.'.$EZKEY.'.'.$a[1].'.0';
		$url=preg_replace('#&spm=\d+\.\d+\.\d+\.\d+#','&spm='.$spm,$url);
	}
	else{
		global $webset;
		$key=$webset['appkey'][0]['key'];
		$url.='&spm=2014.'.$EZKEY.'.'.$key.'.0';
		unset($webset);
	}
	return $url;
}

function ez_strtotime($datetime){
    if($datetime>'2038-01-19 11:14:07'){
    	$a=explode(' ',$datetime);
    	$date=$a[0];
    	if(isset($a[1])){
    		$time=$a[1];
    	}
    	else{
    		$time='00:00:00';
    	}

    	$b=explode('-',$date);

    	$ceil=ceil(($b[0]-2038)/68);
    	$liuba=0;
    	for($i=1;$i<$ceil;$i++){
    		$liuba+=2147483647;
    	}

    	$date_y=$b[0]-2038-($ceil-1)*68+1970;
    	$date_m=$b[1];
    	$date_d=$b[2];
    	$b=explode(':',$time);
    	$time_h=$b[0];
    	$time_i=$b[1];
    	$time_s=$b[2];
    	return 2147483647+strtotime($new_datetime=$date_y.'-'.$date_m.'-'.$date_d.' '.$time_h.':'.$time_i.':'.$time_s)+2793600+$liuba;
    }
    else{
    	$t=strtotime($datetime);
		return $t<0?0:$t;
    }
}

function ez_date($strtime,$type=1){
	if($strtime>2147483647){

		$ceil=ceil(($strtime-2147483647)/2147483647);
		$liuba=0;
    	for($i=1;$i<$ceil;$i++){
    		$liuba+=1;
    	}

	    $datetime=date('Y-m-d H:i:s',$strtime-2147483647-2793600-$liuba*2147483647);
        $a=explode(' ',$datetime);
    	$date=$a[0];
    	$time=$a[1];
    	$b=explode('-',$date);
    	$date_y=$b[0]-1970+2038+$liuba*68;
    	$date_m=$b[1];
    	$date_d=$b[2];
    	$b=explode(':',$time);
    	$time_h=$b[0];
    	$time_i=$b[1];

    	$time_s=$b[2];
    	if($type==1){
    		return $date_y.'-'.$date_m.'-'.$date_d.' '.$time_h.':'.$time_i.':'.$time_s;
    	}
    	elseif($type==2){
    		return $date_y.'-'.$date_m.'-'.$date_d;
    	}
	}
	else{
		if($type==1){
		    $t= date('Y-m-d H:i:s',$strtime);
			if($t=='1970-01-01 08:00:00'){
				$t='';
			}
		}
		elseif($type==2){
		    $t= date('Y-m-d',$strtime);
			if($t=='1970-01-01'){
				$t='';
			}
		}
		return $t;
	}
}

function beijing_time(){
	$timeac='http://www.time.ac.cn/timeflash.asp?user=flash';
	$time_arr=ez_get_xml($timeac);
	if(is_array($time_arr)){
		$cur_datetime=$time_arr['time']['year'].'-'.$time_arr['time']['month'].'-'.$time_arr['time']['day'].' '.$time_arr['time']['hour'].':'.$time_arr['time']['minite'].':'.$time_arr['time']['second'];
		$cur_time=strtotime($cur_datetime);
	}
	else{
		$cur_time=0;
	}
	return $cur_time;
}

function get_domain($url='') {
	if($url==''){
		$url=$_SERVER['HTTP_HOST'];
	}
	
	if(preg_match('#^http://#',$url)){
		$url=str_replace('http://','',$url);
	}
	
	if(preg_match('#^localhost#',$url) || preg_match('/127\.\d+\.\d+\.\d+/',$url) || preg_match('/192\.168\.\d+\.\d+/',$url) || preg_match('/172\.16|31\.\d+\.\d+/',$url)){
		return 'localhost';
	}

	$a=explode('/',$url);
	$url=$a[0];
	preg_match('/^(\d+\.\d+\.\d+\.\d+)/',$url,$a);
	if(isset($a[1])){
		return $a[1];
	}

	$pattern = DOMAIN_PREG;
	preg_match($pattern, $url, $matches);
	if (count($matches) > 0) {
		$domain=$matches[0];
	} else {
		$rs = parse_url($url);
		$main_url = $rs["host"];
		if (!strcmp(long2ip(sprintf("%u", ip2long($main_url))), $main_url)) {
			return $main_url;
		} else {
			$arr = explode(".", $main_url);
			$count = count($arr);
			$endArr = array (
				"com",
				"net",
				"org",
				"3322"
			); //com.cn  net.cn 等情况
			if (in_array($arr[$count -2], $endArr)) {
				$domain = $arr[$count -3] . "." . $arr[$count -2] . "." . $arr[$count -1];
			} else {
				$domain = $arr[$count -2] . "." . $arr[$count -1];
			}
		}
	}
	return $domain;
}

function iptocity($ip=''){
	if($ip==''){$ip=get_client_ip();}
	if(preg_match('/127\.0\.\d+\.\d+/',$ip)==1){
		return '本地';
	}
	$url='http://ip.taobao.com/service/getIpInfo.php?ip='.$ip;
	$a=ez_get_json($url);
	return str_replace('市','',$a['data']['city']);
}

function mobiletocity($mobile){
	if(reg_mobile($mobile)==0){
		return 0;
	}
	$url='http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode='.$mobile.'&userID=';
	$a=ez_get($url);
	preg_match('#<string xmlns="http://WebXml.com.cn/">\d+：(.*)</string>#',$a,$b);
	return $b[1];
}

function ez_crc32($str){
	return (float)sprintf("%u\n", crc32($str));
}

function StopAttack($ArrPGR=array()){
	if(empty($ArrPGR)){
		if(isset($_GET['token']) && TIME-authcode($_GET['token'],'DECODE')<10){
			return true;
		}
		if(isset($_POST['token']) && TIME-authcode($_POST['token'],'DECODE')<10){
			return true;
		}
		check_attack($_GET);
		check_attack($_POST);
	}
	else{
		if(isset($ArrPGR['token']) && TIME-authcode($ArrPGR['token'],'DECODE')<10){
			return true;
		}
		check_attack($ArrPGR);
	}
}

function check_attack(&$array){
	$filter="[\'\"\;\*\<\>]+.*\b(on)[a-zA-Z]{3,15}[\s\r\n\v\f]*\=|\b(expression)\(|<script[\s\\\\\/]*.*>|(<!\[cdata\[)|\b(eval|alert|prompt|msgbox)\s*\(|url\((\#|data|javascript)|([^{\s]{1}.+(select|update|insert((\/\*[\S\s]*?\*\/)|(\s)|(\+))+into).+?(from|set)((\/\*[\S\s]*?\*\/)|(\s)|(\+))+)|[^{\s]{1}.+(create|delete|drop|truncate|rename|desc)((\/\*[\S\s]*?\*\/)|(\s)|(\+))+(table|from|database)((\/\*[\S\s]*?\*\/)|(\s)|(\+))|(into((\/\*[\S\s]*?\*\/)|\s|\+)+(dump|out)file\b)|\bsleep\((\s*)(\d*)(\s*)\)|benchmark\(([^\,]*)\,([^\,]*)\)|\b(declare|set|select)\b.*@|union\b.*(select|all)\b|(select|update|insert|create|delete|drop|grant|truncate|rename|exec|desc|from|table|database|set|where)\b.*((charset|ascii|bin|char|uncompress|concat|concat_ws|conv|export_set|hex|instr|left|load_file|locate|mid|sub|substring|oct|reverse|right|unhex)\(|(master\.\.sysdatabases|msysaccessobjects|msysqueries|sysmodules|mysql\.db|sys\.database_name|information_schema\.|sysobjects|sp_makewebtask|xp_cmdshell|sp_oamethod|sp_addextendedproc|sp_oacreate|xp_regread|sys\.dbms_export_extension))|(..)[^&]*((%2500)|(%00))+[^0-9a-fA-F]|((%2500)|(%00))+[\'\"\.]+|\.\.\/\.\.\/";
	foreach($array as $k=>$v){
		if(is_array($v)){
			check_attack($v);
		}
		else{
			if (get_magic_quotes_gpc() == 0) {
				$v = addslashes($v);
			}
			if (preg_match("#".$filter."#is",$v)==1){
				$msg="操作IP: ".$_SERVER["REMOTE_ADDR"]."操作时间: ".strftime("%Y-%m-%d %H:%M:%S")."操作页面:".MOD.'_'.ACT."提交方式: ".$_SERVER["REQUEST_METHOD"];
				create_file(EZROOT.'/data/temp/attack/'.date('Y-m-d').'.txt',$msg."\r\n".$v."\r\n",1,1);
        		ez_exit("what are you doing man!");
			}
			$array[$k]=$v;
		}
	}
}

function php2js_array($array,$name){
	if(empty($array)){return false;}
	$enter="\r\n";
	echo $name."=new Array();".$enter;
	foreach($array as $k=>$v){
		echo $name."['".$k."']='".$v."';".$enter;
	}
}

function php2js_object($array,$name){
	if(empty($array)){return false;}
	$enter="\r\n";
	echo $name."=new Object();".$enter;
	foreach($array as $k=>$v){
		echo $name."['".$k."']='".$v."';".$enter;
	}
}

function str2arr($str,$num){
	$re=array();
	$a='';
	if(is_string($str)){
		$arr=explode(',',$str);
	}
	else{
		$arr=$str;
	}

	$c=count($arr);
	if($c>$num){
		$i=0;
		foreach($arr as $v){
			$a.=$v.',';
			$i++;
			if($i==$num){
				$a=preg_replace('/,$/','',$a);
				$re[]=$a;
				$a='';
				$i=0;
			}
		}
		$a=preg_replace('/,$/','',$a);
		if($a!=''){
			$re[]=$a;
		}
	}
	else{
		$re[]=$str;
	}
	return $re;
}

function randsort($list,$jishu=4){
	$cnt=count($list)-1;
	$pos=ceil($cnt/$jishu);
	for($m=$pos,$n=$cnt;$m<$cnt-$pos;$m++,$n--){
		$temp=$list[$m];
		$list[$m]=$list[$n];
		$list[$n]=$temp;
	}
	for($m=0,$n=$cnt;$m<$cnt-2;$m+=2,$n--){
		$temp=$list[$m];
		$list[$m]=$list[$n];
		$list[$n]=$temp;
	}
	return $list;
}

function split_word($title){
	if(!class_exists('SplitWord')){
		include(EZROOT.'/comm/splitword.class.php');
	}
	$sp=fs('SplitWord');
	$sp = new SplitWord();
	$sp->SetSource($title);
	$sp->StartAnalysis();
	$a=$sp->GetFinallyIndex();
	return $a;
}

function rand_title($title,$num=1){
	$a=split_word($title);
	for($i=0;$i<$num;$i++){
		$a=randsort($a);
	}
	return implode('',$a);
}


?>